package com.aurora.source.authority.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aurora.source.R;
import com.aurora.source.base.BasePresenter;
import com.aurora.source.base.BaseWhiteToolbarActivity;
import com.aurora.source.base.WebViewActivity;
import com.aurora.source.widget.flowlayout.CreateDialogEditSureCancel;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CreateYardActivity extends BaseWhiteToolbarActivity {

    @BindView(R.id.button)
    AppCompatButton button;
    @BindView(R.id.iv_image)
    ImageView ivImage;
    @BindView(R.id.tv_name)
    TextView tvName;
    private String traceabilityCode;
    private String productName;
    private Bitmap bitmap;

    @Override
    public BasePresenter attach() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_create_yard;
    }

    @Override
    public void initData(@Nullable Bundle bundle) {
        traceabilityCode = getIntent().getStringExtra("traceabilityCode");
        productName = getIntent().getStringExtra("productName");
        tvName.setText(productName);

    }

    @Override
    public void initView(Bundle savedInstanceState, View contentView) {
        simpleToolbar.setMainTitle("商品管理-生成溯源码");
        simpleToolbar.setLeftVisibility(View.VISIBLE);
        /*simpleToolbar.setRightTitleText("保存");
        simpleToolbar.setRightTitleColor(Color.WHITE);
        simpleToolbar.setRightTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savePic(bitmap);
            }
        });
*/
        ViewTreeObserver vto2 = ivImage.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    ivImage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                bitmap = CodeUtils.createImage(traceabilityCode + "", ivImage.getWidth(), ivImage.getHeight(), null);
                ivImage.setImageBitmap(bitmap);
            }
        });
    }

    @Override
    public void doBusiness() {
        ivImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("title","商品溯源信息");
                bundle.putString("url",traceabilityCode);
                gotoActivity(WebViewActivity.class,false,bundle);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button:
         //打印 popWindow();
                savePic(bitmap);
                break;
        }
    }

    private void popWindow() {
        final CreateDialogEditSureCancel rxDialogSureCancel = new CreateDialogEditSureCancel(activity);
        rxDialogSureCancel.setOnSureClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //   String number =  rxDialogSureCancel.getEtNumber().getText().toString();

            }
        });
        rxDialogSureCancel.show();
        rxDialogSureCancel.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.show();

    }


    /**
     * 保存图片到文件
     *
     * @param bitmap
     */
    private void savePic(Bitmap bitmap) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "codepicture");
        if (!appDir.exists()) {
            appDir.mkdir();
        }

        String fileName = productName + ".jpg";
        File file = new File(appDir, fileName);
        FileOutputStream out;

        try {
            out = new FileOutputStream(file);

            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

            out.flush();
            out.close();
            Toast.makeText(this, "图片已保存到:" + appDir.getAbsolutePath(), Toast.LENGTH_LONG)
                    .show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "保存失败", Toast.LENGTH_LONG)
                    .show();
        } catch (IOException e) {
            Toast.makeText(this, "保存失败", Toast.LENGTH_LONG)
                    .show();
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(this.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));


    }
}
